package com.personnalManagerSystem.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author liqing
 * @Date: 2022/3/27 12:54
 * @Description  用户人事管理系统人员登录和登出
 */
@Controller
@RequestMapping("/login")
public class LoginController {
    //用户登录
    @RequestMapping("/check")
    @ResponseBody
    public Map<String,Object> login(@RequestParam(value = "username",required = false)String username,
                                    @RequestParam(value = "password",required = false) String password){
        System.out.println("登录名:"+username);
        System.out.println("密码:"+password);
        Map<String,Object> map = new HashMap<String,Object>();
        //1.获取主题
        Subject subject = SecurityUtils.getSubject();
        //2.通过用户名和密码创建安全令牌
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        //3.检测是否已经登录
        if(subject.isAuthenticated()){
            //登录
            map.put("code",403);
            map.put("state","error");
            map.put("msg","已经登录,请勿重复登陆,谢谢!");
        }
        //未登录,则进行登录
        try{
            subject.login(token);
            map.put("code",200);
            map.put("state","success");
            map.put("msg","登录成功");
        }catch(UnknownAccountException accountException){ //用户名错误
            map.put("code",201);
            map.put("state","error");
            map.put("msg","用户名错误");
        }catch(IncorrectCredentialsException credentialsException){ //密码错误
            map.put("code",202);
            map.put("state","error");
            map.put("msg","密码错误");
        }catch(AuthenticationException authenticationException){ //认证错误
            map.put("code",202);
            map.put("state","error");
            map.put("msg","认证错误");
        }catch(Exception exception){ //其他错误
            map.put("code",500);
            map.put("state","error");
            map.put("msg","其他错误");

        }

        return map;
    }
    //退出登录
    @RequestMapping("/logout")
    public String logout(){
        SecurityUtils.getSubject().logout();
        return "login";
    }



}
